package org.amphiprion.descentv2assistant;

import java.util.List;

import org.amphiprion.descentv2assistant.dao.xml.LanguageXmlDao;
import org.amphiprion.descentv2assistant.dao.xml.ProductXmlDao;
import org.amphiprion.descentv2assistant.entity.Language;
import org.amphiprion.descentv2assistant.entity.Product;
import org.amphiprion.descentv2assistant.ui.fragment.HeroListFragment;
import org.amphiprion.descentv2assistant.ui.fragment.LieutenantListFragment;
import org.amphiprion.descentv2assistant.ui.fragment.MonsterListFragment;
import org.amphiprion.descentv2assistant.util.PreferenceUtil;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Environment;
import android.preference.CheckBoxPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.PreferenceManager;
import android.preference.PreferenceScreen;
import android.util.Log;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockPreferenceActivity;
import com.actionbarsherlock.view.MenuItem;

public class SettingActivity extends SherlockPreferenceActivity implements SharedPreferences.OnSharedPreferenceChangeListener {
	private boolean mustRefreshLists;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		addPreferencesFromResource(R.xml.settings);

		getSupportActionBar().setDisplayHomeAsUpEnabled(true);
		getSupportActionBar().setDisplayShowHomeEnabled(false);
		getSupportActionBar().setBackgroundDrawable(getResources().getDrawable(R.drawable.bg_support_bar));

		final SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(PreferenceUtil.context);
		sharedPref.registerOnSharedPreferenceChangeListener(this);

		// onSharedPreferenceChanged(sharedPref, PreferenceUtil.KEY_PREF_NOTIF_RULE);
		// onSharedPreferenceChanged(sharedPref, PreferenceUtil.KEY_PREF_UPCOMING_DAY);

		Preference restoreXmlPref = findPreference(PreferenceUtil.KEY_PREF_RESTORE_XML);
		restoreXmlPref.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {

			@Override
			public boolean onPreferenceClick(Preference preference) {
				new AlertDialog.Builder(SettingActivity.this).setIcon(android.R.drawable.ic_dialog_alert).setTitle(R.string.restore_xml).setMessage(R.string.restore_xml_sumary)
						.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog, int which) {

								App.restoreXmls();

								Toast.makeText(SettingActivity.this, getResources().getString(R.string.xml_restore_done) + "\n" + Environment.getExternalStorageDirectory() + ApplicationConstants.DIRECTORY, Toast.LENGTH_LONG).show();

								MonsterListFragment.sThis.initData();
								HeroListFragment.sThis.initData();
								LieutenantListFragment.sThis.initData();
							}

						}).setNegativeButton(R.string.no, null).show();

				return true;
			}
		});

		// Products
		PreferenceScreen productScr = (PreferenceScreen) findPreference(PreferenceUtil.KEY_PREF_PRODUCT_LIST);

		List<Product> products = ProductXmlDao.getInstance().getProducts();
		for (final Product p : products) {
			CheckBoxPreference cb = new CheckBoxPreference(this);
			cb.setPersistent(false);
			cb.setTitle(p.getName());
			// cb.setDefaultValue(sharedPref.getBoolean("PRODUCT_OWNED_" + p.getId(), true));
			// cb.setChecked(sharedPref.getBoolean("PRODUCT_OWNED_" + p.getId(), true));
			cb.setDefaultValue(p.isOwned());
			cb.setChecked(p.isOwned());
			productScr.addPreference(cb);
			cb.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {

				@Override
				public boolean onPreferenceChange(Preference preference, Object newValue) {
					Editor editor = sharedPref.edit();
					editor.putBoolean("PRODUCT_OWNED_" + p.getId(), (Boolean) newValue);
					editor.commit();
					p.setOwned((Boolean) newValue);
					mustRefreshLists = true;

					return true;
				}
			});
		}

		// Laguages
		ListPreference languageScr = (ListPreference) findPreference(PreferenceUtil.KEY_PREF_LANGUAGE_CHOICE);

		List<Language> languages = LanguageXmlDao.getInstance().getLanguages();
		String[] ids = new String[languages.size()];
		String[] names = new String[languages.size()];
		String defaultValue = null;
		for (int i = 0; i < languages.size(); i++) {
			Language l = languages.get(i);
			names[i] = l.getName();
			ids[i] = l.getId();

			if (PreferenceUtil.getLanguage().equals(l.getId())) {
				defaultValue = l.getId();
			}
		}
		languageScr.setEntries(names);
		languageScr.setEntryValues(ids);
		languageScr.setDefaultValue(defaultValue);
		languageScr.setValue(defaultValue);
		languageScr.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {

			@Override
			public boolean onPreferenceChange(Preference preference, Object newValue) {
				mustRefreshLists = true;
				PreferenceUtil.setLanguage("" + newValue);
				App.clearInMemoryXmls();
				return true;

			}
		});
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			onBackPressed();
			break;
		}
		return true;
	}

	@Override
	public void onBackPressed() {
		if (mustRefreshLists) {
			if (HeroListFragment.sThis != null) {
				HeroListFragment.sThis.initData();
			}
			if (MonsterListFragment.sThis != null) {
				MonsterListFragment.sThis.initData();
			}
		}
		mustRefreshLists = false;
		super.onBackPressed();
	}

	@Override
	public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
		sharedPreferences.edit().commit();
		// if (key.equals(PreferenceUtil.KEY_PREF_NOTIF_RULE)) {
		// String[] strValues = getResources().getStringArray(R.array.pref_day_upcoming_notif_value);
		// String[] strTitles = getResources().getStringArray(R.array.pref_day_upcoming_notif_title);
		// updateSummary(sharedPreferences, key, strValues, strTitles, "0");
		// } else if (key.equals(PreferenceUtil.KEY_PREF_UPCOMING_DAY)) {
		// String[] strValues = getResources().getStringArray(R.array.pref_day_upcoming_value);
		// String[] strTitles = getResources().getStringArray(R.array.pref_day_upcoming_title);
		// updateSummary(sharedPreferences, key, strValues, strTitles, "7");
		// }
		//
		// if (key.equals(PreferenceUtil.KEY_PREF_UPCOMING_WATCHED) || key.equals(PreferenceUtil.KEY_PREF_UPCOMING_DAY)) {
		// if (UpcomingEpisodeListFragment.sThis != null) {
		// UpcomingEpisodeListFragment.sThis.initData();
		// }
		// }
		Log.d(ApplicationConstants.PACKAGE, "onSharedPreferenceChanged:" + key);
	}

	private void updateSummary(SharedPreferences sharedPreferences, String key, String[] values, String[] summaries, String defaultValue) {
		Preference rule = findPreference(key);
		String val = sharedPreferences.getString(key, defaultValue);
		for (int i = 0; i < values.length; i++) {
			if (values[i].equals(val)) {
				rule.setSummary(summaries[i]);
				break;
			}
		}

	}
}